<template>
  <el-upload
    v-loading="loading"
    class="uploader"
    :disabled="disabled"
    :accept="props.accept"
    :before-upload="beforeUpload"
    :http-request="httpRequest"
    :show-file-list="false"
  >
    <slot name="tip"></slot>
    <template #trigger>
      <el-button plain :disabled="disabled">
        <el-icon>
          <Upload />
        </el-icon>
        <span>上传文件</span>
      </el-button>
    </template>
    <slot></slot>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue';

import { fileService } from '@/api/file';
import moment from 'moment';
import type { UploadInstance, UploadProps, UploadUserFile, UploadRawFile } from 'element-plus';

const props = defineProps({
  accept: {
    type: String,
    default: '.pdf,.doc,.docx,.jpg,.png',
  },
  size: {
    type: Number,
    default: 10,
  },
  uploadUrl: {
    typeof: String,
    default: '/robot-api/admin/file/upload',
  },
  fileNames: {
    typeof: String,
    default: 'files',
  },
  listType: {
    typeof: String,
    default: 'picture-list',
  },
  files: {
    type: Array,
    default: [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const upload = ref<UploadInstance>();
const loading = ref(false);
const beforeUpload = (file) => {
  return true;
};

const httpRequest: any = (data) => {
  const file = data.file;
  const arr = file.name.split('.');
  const accept = arr[arr.length - 1];
  const formData = new FormData();
  const fileName = moment().format('YYYYMMDD') + Math.round((Math.random() + 0.1) * 100000) + '.' + accept;
  formData.append('file', file);
  fileService.upLoad(formData, props.uploadUrl).then((res) => {
    if (res.success) {
      const fileSaveDto = {
        name: fileName,
        url: res.data,
        // fileId: props.files.length + 1,
      };
      emit('update:files', [...props.files, fileSaveDto]);
    }
  });
};

const fileList = ref([]);
// fileList.value = [...props.files];
// watch(
//   () => props.files,
//   (val) => {
//     fileList.value = [...val];
//   },
//   { deep: true },
// );
const sessionToken = ref(null);
const fileUrl = ref('');
const emit = defineEmits(['update:files']);
</script>
<style lang="scss" scoped>
.uploader {
  width: 100%;
}
</style>
